<template>
  <div class="page-container">
    <el-card shadow="never">
      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="handleAdd">新增权限</el-button>
        <el-button type="warning" @click="refreshTree">
          {{ isTreeView.value ? '恢复列表' : '查看树形结构' }}
        </el-button>
      </div>

      <!-- 权限表格（树形结构） -->
      <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          row-key="id"
          default-expand-all
          :tree-props="{ children: 'children' }"
          v-loading="loading"
      >
        <el-table-column align="center" prop="name" label="权限名称" width="200"/>
        <el-table-column align="center" prop="code" label="权限编码" width="180"/>
        <el-table-column align="center" prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="row.type === 'menu' ? 'primary' : 'success'">
              {{ row.type === 'menu' ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="url" label="路径/URL"/>
        <el-table-column align="center" prop="method" label="方法" width="100"/>
        <el-table-column align="center" label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog :title="form.id ? '编辑权限' : '新增权限'" v-model="showDialog" width="50%">
      <el-form :model="form" label-width="90px" ref="formRef" :rules="rules">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" placeholder="如 用户管理"/>
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="form.code" placeholder="如 user:list"/>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="menu">菜单</el-radio>
            <el-radio label="button">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级权限">
          <el-cascader
              v-model="parentId"
              :options="permissionOptions"
              :props="{ value: 'id', label: 'name', checkStrictly: true, emitPath: false }"
              clearable
              placeholder="请选择上级（默认为根）"
          />
        </el-form-item>
        <el-form-item label="路径URL" prop="url">
          <el-input v-model="form.url" placeholder="前端路由或后端API路径"/>
        </el-form-item>
        <el-form-item label="HTTP方法" v-if="form.type === 'button'">
          <el-select v-model="form.method" placeholder="选择方法">
            <el-option label="GET" value="GET"/>
            <el-option label="POST" value="POST"/>
            <el-option label="PUT" value="PUT"/>
            <el-option label="DELETE" value="DELETE"/>
          </el-select>
        </el-form-item>
        <el-form-item label="图标" v-if="form.type === 'menu'">
          <el-input v-model="form.icon" placeholder="如 el-icon-user"/>
        </el-form-item>
        <el-form-item label="排序" v-if="form.type === 'menu'">
          <el-input-number v-model="form.sort" :min="0" :max="999"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import request from '@/api/request';
import {ElMessage, ElMessageBox} from "element-plus";

const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

const showDialog = ref(false);
const formRef = ref();
const form = ref({
  id: null,
  name: '',
  code: '',
  type: 'menu',
  parentId: 0,
  url: '',
  method: '',
  icon: '',
  sort: 0,
  status: 1
});
const parentId = ref(); // 用于 cascader 回显
const permissionOptions = ref([]); // 扁平化权限列表

const rules = {
  name: [{required: true, message: '请输入权限名称', trigger: 'blur'}],
  code: [{required: true, message: '请输入权限编码', trigger: 'blur'}],
  type: [{required: true, message: '请选择类型', trigger: 'change'}]
};

// 获取权限分页数据（扁平）
const fetchData = () => {
  loading.value = true;
  request.get('/sys-permission/page', {
    params: {page: currentPage.value, size: pageSize.value}
  }).then(res => {
    const data = res.data.data;
    tableData.value = data.records;
    total.value = data.total;
  }).finally(() => {
    loading.value = false;
  });
};

// 获取所有权限用于 cascader
const loadAllPermissions = () => {
  request.get('/sys-permission/menus').then(res => {
    permissionOptions.value = res.data.data || [];
  });
};

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

const handleAdd = () => {
  loadAllPermissions(); // 加载所有权限用于选择

  form.value = {
    id: null,
    name: '',
    code: '',
    type: 'menu',
    parentId: 0,
    url: '',
    method: '',
    icon: '',
    sort: 0,
    status: 1
  };
  parentId.value = null;
  showDialog.value = true;
};

const handleEdit = (row) => {
  loadAllPermissions(); // 加载所有权限用于选择

  form.value = {...row};
  parentId.value = row.parentId === 0 ? null : row.parentId;
  showDialog.value = true;
};

const handleDelete = (id) => {
  ElMessageBox.confirm('删除权限会同时删除其子权限，确定吗？', '警告', {type: 'warning'}).then(() => {
    request.delete(`/sys-permission/${id}`).then(() => {
      ElMessage.success('删除成功');
      fetchData();
    });
  }).catch(() => {
  });
};

const submitForm = () => {
  formRef.value.validate(valid => {
    if (!valid) return;

    const f = {...form.value};
    f.parentId = parentId.value || 0;

    const api = f.id ? request.put : request.post;
    api('/sys-permission', f).then(() => {
      ElMessage.success(f.id ? '更新成功' : '添加成功');
      showDialog.value = false;
      fetchData();
    });
  });
};

// 新增响应式变量
const isTreeView = ref(false); // 是否处于树形视图模式

// 刷新树功能
const refreshTree = () => {
  if (isTreeView.value) {
    // 如果已在树视图，点击则回到分页列表
    isTreeView.value = false;
    ElMessage.info('已切换回分页列表');
    fetchData(); // 重新加载分页数据
  } else {
    // 进入树形视图
    loading.value = true;
    isTreeView.value = true;
    request.get('/sys-role-permission/tree/all')
        .then(res => {
          const treeData = res.data.data || [];
          tableData.value = treeData;
          ElMessage.success(`已加载 ${treeData.length ? '完整权限树' : '空树'}，共展示 ${countNodes(treeData)} 个节点`);
        })
        .catch(() => {
          ElMessage.error('获取权限树失败');
          isTreeView.value = false;
          fetchData(); // 回退到列表
        })
        .finally(() => {
          loading.value = false;
        });
  }
};

// 辅助函数：统计树中所有节点数量（用于提示）
const countNodes = (nodes) => {
  return nodes.reduce((sum, node) => {
    return sum + 1 + (node.children ? countNodes(node.children) : 0);
  }, 0);
};

onMounted(() => {
  fetchData();
  loadAllPermissions(); // 加载所有权限用于选择
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}
</style>
